package com.writeEvent;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * @author 罗俊华
 * @date 2021/8/24 - 10:31 上午
 */
@Slf4j
public class WriteClient {

    public static void main(String[] args) throws IOException {
        try (SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8081));
             FileChannel fileChannel = new RandomAccessFile("/Users/luo/temp/linux.iso", "rw").getChannel()) {


            ByteBuffer byteBuffer = ByteBuffer.allocate(4 * 1024 * 1024);
            int read = 0;
            ByteBuffer fileSizeBuffer = ByteBuffer.allocate(8);
            int count = socketChannel.read(fileSizeBuffer);
            fileSizeBuffer.flip();
            long fileSizeBufferLong = fileSizeBuffer.getLong();
            log.debug("读取到{}个字节，此文件的大小为【{}】MB", count, fileSizeBufferLong / 1024 / 1024);

            while ((read += socketChannel.read(byteBuffer)) < fileSizeBufferLong) {
                log.debug("已下载{}MB 数据", read / 1024 / 1024);
                byteBuffer.flip();
                fileChannel.write(byteBuffer);
                byteBuffer.compact();
            }
            log.info("下载完成");

        }
    }
}
